const express = require('express');
const { body, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const Role = require('../models/Role');
const auth = require('../middleware/auth');

const router = express.Router();

// 验证错误处理中间件
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: errors.array()
    });
  }
  next();
};

// 用户登录
router.post('/login', [
  body('username').notEmpty().withMessage('用户名不能为空'),
  body('password').notEmpty().withMessage('密码不能为空'),
  handleValidationErrors
], async (req, res) => {
  try {
    console.log('登录请求参数---',req.body)
    const { username, password } = req.body;
    
    // 查找用户
    const user = await User.findByUsername(username);
    if (!user) {
      return res.status(500).json({
        success: false,
        message: '账户不存在'
      });
    }
    
    // 验证密码
    const isValidPassword = await User.verifyPassword(password, user.password);
    if (!isValidPassword) {
      return res.status(500).json({
        success: false,
        message: '密码错误'
      });
    }
    
    // 检查用户状态
    if (user.status !== 'active') {
      return res.status(401).json({
        success: false,
        message: '账户已被禁用，请联系管理员'
      });
    }
    
    // 获取用户角色和权限
    let role = null;
    let permissions = [];
    let menus = [];
    const Menu = require('../models/Menu');
    
    if (user.role_id) {
      role = await Role.findById(user.role_id);
      if (role) {
        permissions = await Role.getPermissions(user.role_id);
      }
    }
    
    // admin用户返回全量菜单和全量权限
    console.log('登录的用户',user.username,'查询到的角色--',role)
    if (user.username === 'admin' || (role && role.code === 'admin')) {
      const allMenus = await Menu.findAll();
      menus = Menu.buildMenuTree(allMenus);
      permissions = allMenus.filter(m => m.permission).map(m => m.permission);
    } else {
      if (user.role_id) {
        try {
          const dbMenus = await Menu.findByRoleId(user.role_id);
          menus = Menu.buildMenuTree(dbMenus);
          // 权限过滤逻辑
          const filterMenusByPermission = (menuList) => {
            return menuList.filter(menu => {
              if (menu.permission) {
                const hasPermission = permissions.includes(menu.permission);
                if (!hasPermission) {
                  return false;
                }
              }
              if (menu.children && menu.children.length > 0) {
                menu.children = filterMenusByPermission(menu.children);
                if (menu.children.length === 0 && !menu.permission) {
                  return false;
                }
              }
              return true;
            });
          };
          menus = filterMenusByPermission(menus);
        } catch (error) {
          console.error('获取菜单失败:', error);
          menus = [];
        }
      }
    }
    
    // 生成JWT令牌
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        role_id: user.role_id,
        department_id: user.department_id
      },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );
    
    // 返回用户信息（不包含密码）
    const { password: _, ...userInfo } = user;
    
    res.json({
      success: true,
      message: '登录成功',
      data: {
        user: {
          ...userInfo,
          role: role ? { id: role.id, name: role.name, code: role.code } : null,
          permissions
        },
        token,
        menus
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '登录失败'
    });
  }
});

// 用户注册
router.post('/register', [
  body('username').isLength({ min: 3, max: 50 }).withMessage('用户名长度必须在3-50个字符之间'),
  body('password').isLength({ min: 6 }).withMessage('密码长度至少6个字符'),
  body('email').isEmail().withMessage('邮箱格式不正确'),
  body('phone').optional().isMobilePhone('zh-CN').withMessage('手机号格式不正确'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { username, password, email, phone } = req.body;
    
    // 检查用户名是否已存在
    const existingUser = await User.findByUsername(username);
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }
    
    // 创建用户（默认角色为普通用户）
    const userData = {
      username,
      password,
      email,
      phone,
      status: 'active',
      role_id: 2, // 默认普通用户角色
      department_id: null
    };
    
    const newUser = await User.create(userData);
    
    // 生成JWT令牌
    const token = jwt.sign(
      {
        id: newUser.id,
        username: newUser.username,
        role_id: newUser.role_id,
        department_id: newUser.department_id
      },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );
    
    // 返回用户信息（不包含密码）
    const { password: _, ...userInfo } = newUser;
    
    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        user: userInfo,
        token
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '注册失败'
    });
  }
});

// 获取当前用户信息
router.get('/me', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 获取用户角色和权限
    let role = null;
    let permissions = [];
    let menus = [];
    const Menu = require('../models/Menu');
    
    if (user.role_id) {
      role = await Role.findById(user.role_id);
      if (role) {
        permissions = await Role.getPermissions(user.role_id);
      }
    }
    
    // admin用户返回全量菜单和全量权限
    if (user.username === 'admin' || (role && role.code === 'admin')) {
      const allMenus = await Menu.findAll();
      menus = Menu.buildMenuTree(allMenus);
      permissions = allMenus.filter(m => m.permission).map(m => m.permission);
    } else {
      if (user.role_id) {
        try {
          const dbMenus = await Menu.findByRoleId(user.role_id);
          menus = Menu.buildMenuTree(dbMenus);
          // 权限过滤逻辑
          const filterMenusByPermission = (menuList) => {
            return menuList.filter(menu => {
              if (menu.permission) {
                const hasPermission = permissions.includes(menu.permission);
                if (!hasPermission) {
                  return false;
                }
              }
              if (menu.children && menu.children.length > 0) {
                menu.children = filterMenusByPermission(menu.children);
                if (menu.children.length === 0 && !menu.permission) {
                  return false;
                }
              }
              return true;
            });
          };
          menus = filterMenusByPermission(menus);
        } catch (error) {
          console.error('获取菜单失败:', error);
          menus = [];
        }
      }
    }
    
    // 返回用户信息（不包含密码）
    const { password: _, ...userInfo } = user;
    
    res.json({
      success: true,
      message: '获取用户信息成功',
      data: {
        ...userInfo,
        role: role ? { id: role.id, name: role.name, code: role.code } : null,
        permissions,
        menus
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取用户信息失败'
    });
  }
});

// 更新当前用户信息
router.put('/me', [
  auth,
  body('email').optional().isEmail().withMessage('邮箱格式不正确'),
  body('phone').optional().isMobilePhone('zh-CN').withMessage('手机号格式不正确'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { email, phone } = req.body;
    const userData = {};
    
    if (email) userData.email = email;
    if (phone) userData.phone = phone;
    
    const updatedUser = await User.update(req.user.id, userData);
    
    // 返回用户信息（不包含密码）
    const { password: _, ...userInfo } = updatedUser;
    
    res.json({
      success: true,
      message: '更新用户信息成功',
      data: userInfo
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新用户信息失败'
    });
  }
});

// 修改当前用户密码
router.patch('/me/password', [
  auth,
  body('oldPassword').notEmpty().withMessage('原密码不能为空'),
  body('newPassword').isLength({ min: 6 }).withMessage('新密码长度至少6个字符'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;
    
    // 获取用户信息
    const user = await User.findById(req.user.id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 验证原密码
    const isValidPassword = await User.verifyPassword(oldPassword, user.password);
    if (!isValidPassword) {
      return res.status(400).json({
        success: false,
        message: '原密码错误'
      });
    }
    
    // 更新密码
    await User.updatePassword(req.user.id, newPassword);
    
    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '修改密码失败'
    });
  }
});

// 用户登出
router.post('/logout', auth, (req, res) => {
  // 在实际项目中，可以将token加入黑名单
  res.json({
    success: true,
    message: '登出成功'
  });
});

// 刷新令牌
router.post('/refresh', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    
    if (!user || user.status !== 'active') {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      });
    }
    
    // 生成新的JWT令牌
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        role_id: user.role_id,
        department_id: user.department_id
      },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );
    
    res.json({
      success: true,
      message: '令牌刷新成功',
      data: { token }
    });
  } catch (error) {
    console.error('刷新令牌错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '刷新令牌失败'
    });
  }
});

module.exports = router;